<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Vue 2 + Layui 组件更新视图示例</title>
  <link rel="stylesheet" href="/LayUi/lib/css/layui.css">
  <script src="https://v2.cn.vuejs.org/js/vue.min.js"></script>
  <script src="/LayUi/lib/layui.js"></script>
</head>
<body>
  <div id="app">
    <form class="layui-form">
      <!-- select 组件 -->
      <div class="layui-form-item">
        <label class="layui-form-label">选择城市</label>
        <div class="layui-input-block">
          <select v-model="selectedCity" @change="updateLayuiForm">
            <option v-for="city in cities" :key="city.value" :value="city.value">{{ city.name }}</option>
          </select>
        </div>
      </div>

      <!-- checkbox 组件 -->
      <div class="layui-form-item">
        <label class="layui-form-label">爱好</label>
        <div class="layui-input-block">
          <input type="checkbox" name="hobby" title="篮球" v-model="hobbies" value="basketball" @change="updateLayuiForm">
          <input type="checkbox" name="hobby" title="足球" v-model="hobbies" value="soccer" @change="updateLayuiForm">
          <input type="checkbox" name="hobby" title="游泳" v-model="hobbies" value="swimming" @change="updateLayuiForm">
        </div>
      </div>
    </form>

    <!-- table 组件 -->
    <table class="layui-table">
      <thead>
        <tr>
          <th>编号</th>
          <th>名称</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in tableData" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td><button @click="removeItem(index)">删除</button></td>
        </tr>
      </tbody>
    </table>
  </div>

  <script>
    new Vue({
      el: '#app',
      data: {
        cities: [
          { value: 'beijing', name: '北京' },
          { value: 'shanghai', name: '上海' },
          { value: 'guangzhou', name: '广州' }
        ],
        selectedCity: '',
        hobbies: [],
        tableData: [
          { id: 1, name: '张三' },
          { id: 2, name: '李四' },
          { id: 3, name: '王五' }
        ]
      },
      methods: {
        updateLayuiForm() {
          // 更新Layui的form渲染
          layui.use('form', function() {
            var form = layui.form;
            form.render(); // 重新渲染所有表单组件
          });
        },
        removeItem(index) {
          // 删除table中的一项
          this.tableData.splice(index, 1);

          console.log("this.tableData",this.tableData);
          // 由于table不是Layui的表单组件，所以不需要调用form.render()
          // 但如果你使用了Layui的table组件，则需要调用table.reload()等方法来更新
        }
      },
      mounted() {
        // 初始化Layui的form模块
        layui.use('form', function() {
          var form = layui.form;
          form.render(); // 初始渲染
        });
      }
    });
  </script>
</body>
</html>
